﻿Shader "Custom/m3dAnimation"
{
	Properties
	{
        _Color ("Color", color) = (1,1,1,1)
		_MainTex ("Texture", 2D) = "white" {}
        _Bump("Normal", 2D) = "bump" {}
	}
	SubShader
	{
		Tags { "RenderQueue" = "Geometry" }

		Pass
		{
            Tags {"LightMode" = "ForwardBase"}
			CGPROGRAM
            #pragma multi_compile_fwdbase
			#pragma vertex vert
			#pragma fragment frag
            #include "Lighting.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float4 uv : TEXCOORD0;
                float3 normal : NORMAL;
                float4 tangent : TANGENT;
			};

			struct v2f
			{
                float4 pos : SV_POSITION;
				float4 uv : TEXCOORD0;
                float4 TtoW1 : TEXCOORD1;
                float4 TtoW2 : TEXCOORD2;
                float4 TtoW3 : TEXCOORD3;
			};

            fixed4 _Color;
			sampler2D _MainTex;
			float4 _MainTex_ST;
            sampler2D _Bump;
            float4 _Bump_ST;
			
			v2f vert (appdata v)
			{
				v2f o;
				o.pos = UnityObjectToClipPos(v.vertex);
				o.uv.xy = TRANSFORM_TEX(v.uv, _MainTex);
                o.uv.zw = TRANSFORM_TEX(v.uv, _Bump);
                float3 worldPos = mul(unity_ObjectToWorld, v.vertex);
                float3 worldNormal = UnityObjectToWorldNormal(v.normal);
                float3 worldTangent = UnityObjectToWorldDir(v.tangent.xyz);
                float3 worldBinormal = normalize(cross(worldNormal, worldTangent) * v.tangent.w);
                o.TtoW1 = float4(worldTangent.x, worldBinormal.x, worldNormal.x, worldPos.x);
                o.TtoW2 = float4(worldTangent.y, worldBinormal.y, worldNormal.y, worldPos.y);
                o.TtoW3 = float4(worldTangent.z, worldBinormal.z, worldNormal.z, worldPos.z);
				return o;
			}
			
			fixed4 frag (v2f i) : SV_Target
			{
                fixed3 worldPos = fixed3(i.TtoW1.w, i.TtoW2.w, i.TtoW3.w);

                fixed3 bump = UnpackNormal(tex2D(_Bump, i.uv.zw));
                bump = normalize(fixed3(dot(bump, i.TtoW1.xyz), dot(bump, i.TtoW2.xyz), dot(bump, i.TtoW3.xyz)));

                fixed3 lightDir = normalize(UnityWorldSpaceLightDir(worldPos));

                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
                fixed3 diffuse = _LightColor0.xyz * saturate(dot(bump, lightDir));
                
				fixed3 texColor = tex2D(_MainTex, i.uv.xy).xyz;

                fixed4 col = fixed4(_Color.rgb * texColor.rgb * (ambient + diffuse), 1);

				return col;
			}
			ENDCG
		}
	}
}
